package cn.lcfms.app.admin.service;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.lcfms.app.admin.bean.ArticleBean;
import cn.lcfms.app.admin.bean.CategoryBean;
import cn.lcfms.app.admin.service.Dao.CommonDao;
import cn.lcfms.bin.Userinfo;
import cn.lcfms.bin.core.Application;
import cn.lcfms.bin.service.BaseService;
import cn.lcfms.utils.StringUtils;
@Service
public class DataService {
	@Autowired
	private CommonDao cd;
	@Transactional
	public boolean saveArticle(ArticleBean article){
		boolean b=true;
		try {
			BaseService service = Application.getService("articles");	
			if(article.getId()==0) {
				article.setAid(Userinfo.get("aid"));
				service.insert(article);
			}else {
				HashMap<String, Object> map=new HashMap<>();
				map.put("id", article.getId());
				map.put("title", article.getTitle());
				map.put("category_id", article.getCategory_id());
				map.put("labels", StringUtils.join(article.getLabels(), ","));	
				map.put("desc", article.getDesc());		
				map.put("details", article.getDetails());
				map.put("aid",Userinfo.get("aid"));
				service.where("id=#{id}");
				service.setData(map);
				service.update("title","category_id","aid","labels","desc","details");
			}
			int id = article.getId();
			if(null!=article.getImgfile()) {
				JSONArray uploads = JSONArray.fromObject(article.getImgfile());
				if(id!=0 && uploads.size()>0){	
					for(int i=0;i<uploads.size();i++){
						JSONObject object = uploads.getJSONObject(i);						
						int fid=(int) object.get("id");
						service.setTable("files");
						service.where("id="+fid);
						service.setData(id,"articles");
						service.update("file_type_id","file_type");
					}
				}
			}	
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return b;
	}	
	
	@Transactional
	public boolean saveCategory(CategoryBean cate){
		boolean b=true;
		try {	
			BaseService service=Application.getService("categories");	
			if(cate.getId()!=0) {
				HashMap<String, Object> map=new HashMap<>();
				map.put("id", cate.getId());
				map.put("title", cate.getTitle());
				map.put("pid", cate.getPid());
				map.put("labels", StringUtils.join(cate.getLabels(), ","));
				map.put("desc", cate.getDesc());
				service.where("id=#{id}");
				service.setData(map);
				service.update("title","pid","labels","desc");			
			}else {
				service.insert(cate);
			}		
			int id = cate.getId();
			if(null!=cate.getImgfile()) {
				JSONArray uploads = JSONArray.fromObject(cate.getImgfile());
				if(id!=0 && uploads.size()>0){	
					for(int i=0;i<uploads.size();i++){
						JSONObject object = uploads.getJSONObject(i);						
						int fid=(int) object.get("id");
						service.setTable("files");
						service.where("id",fid);
						service.setData(id,"categories");
						service.update("file_type_id","file_type");
					}
				}
			}			
		} catch (Exception e) {
			e.printStackTrace();
			b=false;
		}
		return b;
	}
	
	/**
	 * 根据id递归获取栏目
	 * @param id
	 * @return
	 */
	public HashMap<Integer, String> getCategory(int id){
		HashMap<Integer, String> map=new HashMap<>();
		getCategory(id,map);
		return map;
	}
	
	private void getCategory(int id,HashMap<Integer, String> map) {
		BaseService service=Application.getService("categories");
		service.where("id", id);
		HashMap<String, Object> r = service.selectMap();
		if(!r.containsKey("id")) {
			return;
		}
		int pid=(int) r.get("pid");
		String title=(String) r.get("title");
		map.put(id, title);
		if(pid!=0) {
			getCategory(pid,map);
		}
	}
	
	public JSONArray getCategoryFile(int cateId) {
		BaseService service= Application.getService("files");
		service.where("file_type", "categories");
		service.where("file_type_id", cateId);
		List<HashMap<String, Object>> list = service.selectList();
		JSONArray array=new JSONArray();
		for(int i=0;i<list.size();i++) {
			JSONObject object=new JSONObject();
			String type=(String) list.get(i).get("type");
			String original=(String) list.get(i).get("original");			
			object.put("type", type);
			object.put("id", list.get(i).get("id"));
			String path="";
			String[] split = original.split("/");			
			if(type.equals("img")) {
				object.put("url", Application.APP_PATH+"uploadfile/images/"+original);	
				path= Application.ROOT_PATH+"uploadfile"+File.separator+"images"+File.separator+split[0]+File.separator+split[1];
			}else {
				object.put("url", Application.APP_PATH+"uploadfile/file/"+original);
				path= Application.ROOT_PATH+"uploadfile"+File.separator+"file"+File.separator+split[0]+File.separator+split[1];
			}			
			File file=new File(path);
			object.put("size", file.length());
			array.add(object);
		}
		return array;
	}
	
	public JSONArray getArticleFile(int articleId) {
		BaseService service= Application.getService("files");
		service.where("file_type", "articles");
		service.where("file_type_id", articleId);
		List<HashMap<String, Object>> list = service.selectList();
		JSONArray array=new JSONArray();
		for(int i=0;i<list.size();i++) {
			JSONObject object=new JSONObject();
			String type=(String) list.get(i).get("type");
			String original=(String) list.get(i).get("original");			
			object.put("type", type);
			object.put("id", list.get(i).get("id"));
			String path="";
			String[] split = original.split("/");			
			if(type.equals("img")) {
				object.put("url", Application.APP_PATH+"uploadfile/images/"+original);	
				path= Application.ROOT_PATH+"uploadfile"+File.separator+"images"+File.separator+split[0]+File.separator+split[1];
			}else {
				object.put("url", Application.APP_PATH+"uploadfile/file/"+original);
				path= Application.ROOT_PATH+"uploadfile"+File.separator+"file"+File.separator+split[0]+File.separator+split[1];
			}			
			File file=new File(path);
			object.put("size", file.length());
			array.add(object);
		}
		return array;
	}
	/**
	 * 获取文章列表
	 * @param cateId 栏目id
	 * @param rows 每页的行数
	 * @param page 当前页
	 */
	public List<HashMap<String, Object>> getArticleList(int cateId,int rows,int page) {
		BaseService service= Application.getService("categories");
		service.column("id","pid");
		List<HashMap<String, Object>> list = service.selectList();
		List<HashMap<String, Object>> data=new ArrayList<>();
		getIdlist(list,data,cateId);
		StringBuffer where=new StringBuffer();
		for(int i=0;i<data.size();i++) {			
			HashMap<String, Object> map=data.get(i);
			int id=(int)map.get("id");
			where.append(id);
			if(i!=data.size()-1) {
				where.append(",");
			}
		}
		int begin=(page-1)*rows;
		List<HashMap<String, Object>> r = cd.selectArticleList(where.toString(),begin, rows);
		
		return r;
	}
	
	private void getIdlist(List<HashMap<String, Object>> list,List<HashMap<String, Object>> data,int cateId) {
		for(HashMap<String, Object> map:list) {
			int id=(int)map.get("id");
			int pid=(int)map.get("pid");	
			if(id==cateId) {
				data.add(map);
			}
			if(pid==cateId) {
				getIdlist(list,data,id);
			}			
		}
	}
	
	public JSONObject getArticleLastImg(int articleId) {
		BaseService service= Application.getService("files");
		service.where("file_type", "articles");
		service.where("file_type_id", articleId);
		service.where("type", "img");
		service.limit(0, 1);
		service.order("id desc");
		HashMap<String, Object> map = service.selectMap();
		JSONObject object=new JSONObject();
		if(map.size()>0) {
			String original=(String) map.get("original");			
			String thumbnail=(String) map.get("thumbnail");			
			object.put("id", map.get("id"));
			String path="";
			String[] split = original.split("/");			
			object.put("url", Application.APP_PATH+"uploadfile/images/"+original);	
			object.put("thumb", Application.APP_PATH+"uploadfile/images/"+thumbnail);	
			path= Application.ROOT_PATH+"uploadfile"+File.separator+"images"+File.separator+split[0]+File.separator+split[1];		
			File file=new File(path);
			object.put("size", file.length());
		}	
		return object;
	}
	
	public JSONObject getFileById(int id) {
		BaseService service= Application.getService("files");
		service.where("id", id);
		HashMap<String, Object> map = service.selectMap();
		JSONObject object=new JSONObject();
		if(map.size()>0) {
			String type=(String) map.get("type");
			String original=(String) map.get("original");			
			object.put("type", type);
			object.put("id", map.get("id"));
			String path="";
			String[] split = original.split("/");			
			if(type.equals("img")) {
				object.put("url", Application.APP_PATH+"uploadfile/images/"+original);	
				path= Application.ROOT_PATH+"uploadfile"+File.separator+"images"+File.separator+split[0]+File.separator+split[1];
			}else {
				object.put("url", Application.APP_PATH+"uploadfile/file/"+original);
				path= Application.ROOT_PATH+"uploadfile"+File.separator+"file"+File.separator+split[0]+File.separator+split[1];
			}			
			File file=new File(path);
			object.put("size", file.length());
		}
		return object;
	}
	
	public void setPhoto(HttpServletRequest request,Object bean,String key) {
		String[] param = request.getParameterValues(key);
		if(null==param) {
			return;
		}
		JSONArray array=new JSONArray();
		for(String p:param) {
			array.add(p);
		}
		try {
			Field field = bean.getClass().getDeclaredField(key);
			field.setAccessible(true);
			field.set(bean, array.toString());
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
	}
}
